package com.bbcare.mqservice.utils.rockermq;


import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.bbcare.mqservice.service.IIpconfigService;
import com.bbcare.mqservice.service.IMessageService;
import com.bbcare.mqservice.utils.HttpUtil;
import com.bbcare.mqservice.utils.IpUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class RocketmqListener implements MessageListener {

    private static  final Logger logger = LogManager.getLogger();

    /**
     * 由于消费者是多线程的，所以对象要用static+set注入，把对象的级别提升到进程，
     * 这样多个线程就可以共用，但是无法调用父类的方法和变量
     */
   @Autowired
    private IIpconfigService ipconfigService;
    @Autowired
    private IMessageService iMessageService;
    @Override
    public Action consume(Message message, ConsumeContext context) {
        try {
            Long startTime = System.currentTimeMillis();
            byte[] body = message.getBody();
            String msg = new String(body);//获取到接收的消息，由于接收到的是byte数组，所以需要转换成字符串
            com.bbcare.mqservice.entity.Message ms = new com.bbcare.mqservice.entity.Message();
            String result = "fail";
            ms.setOriIp("mq");
            ms.setCreatTime(LocalDateTime.now());
            ms.setType("接收");
            ms.setMessage(msg);
            JSONObject jsonObject = JSON.parseObject(msg);
            String deptId = jsonObject.getString("deptId");
            String ip =  ipconfigService.getIpByDeptId(deptId);
            Long endTime = System.currentTimeMillis();
            try{
                result  =  HttpUtil.postData(ip+"/followup/switchData/mq",msg);
            }catch (Exception ex){
                result  =ex.getMessage();
            }finally {

                ms.setResult(result);
                ms.setEndTime(LocalDateTime.now());
                iMessageService.save(ms);
                logger.info("请求："+msg+"结果:"+result);
            }
            System.out.println("单次消费耗时："+(endTime-startTime)/1000);

        } catch (Exception e) {
            logger.error("MessageListener.consume error:" + e.getMessage(), e);
        }

        logger.info("MessageListener.Receive message");
        //如果想测试消息重投的功能,可以将Action.CommitMessage 替换成Action.ReconsumeLater
        return Action.CommitMessage;
    }


}
